package com.hq.fxh.No3_TuiGuang.MyMoBan.Activity.item;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.AppCompatCheckBox;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Selection;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hq.fxh.CustomerView.switchbutton.SwitchButton;
import com.hq.fxh.No3_TuiGuang.MyMoBan.Activity.AdBannerInfo;
import com.hq.fxh.No3_TuiGuang.MyMoBan.ClearableEidtText;
import com.hq.fxh.R;
import com.hq.fxh.Utils.GlideUtils;
import com.hq.fxh.Utils.SharedPreferenceUtils;


/**
 * @author 大圣
 * @ClassName GraphicAdItem
 * @Description : 图文广告
 * @Created 2015/11/13 0013
 * @Email qwqe601660957@163.com
 */
public class GraphicAdItem extends LinearLayout {

    private FrameLayout flGraphicPicAdd;
    private ImageButton ibClose;
    private TextView tvAdTypeName;

    /** */
    private ImageView ivAd;
    /**
     * 服务名称
     */
    private ClearableEidtText etServiceName;
    /**
     * 服务描述
     */
    private ClearableEidtText etDes;
    /**
     * 链接地址
     */
    private ClearableEidtText etUrl;
    /**
     * 广告介绍
     **/
    private TextView tvDes;
    //  private MerchantToolSysConfigPresenter merchantToolSysConfigPresenter;
    private SwitchButton sbSwitch;
    private TextView tvSwitchInfo;
    private AppCompatCheckBox cbUseSpace;
    boolean flag = false;
    private AdBannerInfo adBannerInfo;
    private AdBannerInfo.AdvertDetailBean Advert_detail;

    public GraphicAdItem(Context context) {
        super(context);
        inflate(context, R.layout.item_graphic_ad, this);
        findView();
        etServiceName.setSingleLine(true);
        etServiceName.setHorizontallyScrolling(true);
        etDes.setSingleLine(true);
        etDes.setHorizontallyScrolling(true);
        tvAdTypeName.setText("图文广告");
/*        merchantToolSysConfigPresenter = new MerchantToolSysConfigPresenter(this);
        merchantToolSysConfigPresenter.attath(getContext());*/
    }

    private SpannableString getClickableSpan(String des, final String url) {
        OnClickListener l = new OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("title", "图文广告");
                bundle.putString("url", url);
                //    IntentUtils.openActivity(getContext(), WebActivity.class, bundle);
            }
        };
        SpannableString spanableInfo = new SpannableString(des + "查看详情");
        int start = spanableInfo.toString().indexOf("查看详情");
        int end = spanableInfo.length();
        spanableInfo.setSpan(new Clickable(l), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spanableInfo.setSpan(new ForegroundColorSpan(getContext().getResources().getColor(R.color.new_red)), start, end,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spanableInfo;
    }


    class Clickable extends ClickableSpan implements OnClickListener {
        private final OnClickListener mListener;

        public Clickable(OnClickListener l) {
            mListener = l;
        }

        @Override
        public void onClick(View v) {
            mListener.onClick(v);
        }
    }

    public void findView() {
        flGraphicPicAdd = (FrameLayout) findViewById(R.id.flGraphicPicAdd);
        ibClose = (ImageButton) findViewById(R.id.ibClose);
        tvAdTypeName = (TextView) findViewById(R.id.tvAdTypeName);
        ivAd = (ImageView) findViewById(R.id.ivAd);
        etServiceName = (ClearableEidtText) findViewById(R.id.etServiceName);
        etDes = (ClearableEidtText) findViewById(R.id.etDes);
        etUrl = (ClearableEidtText) findViewById(R.id.etUrl);
        tvDes = (TextView) findViewById(R.id.tvDes);
        sbSwitch = (SwitchButton) findViewById(R.id.sbSwitch);
        tvSwitchInfo = (TextView) findViewById(R.id.tvSwitchInfo);
        cbUseSpace = (AppCompatCheckBox) findViewById(R.id.cbUseSpace);
    }

    public void setAdInfo(final AdBannerInfo info) {
        adBannerInfo = info;
        Advert_detail = info.getAdvert_detail();
        if (Advert_detail != null) {
            etServiceName.setText(Advert_detail.getName());
            etDes.setText(Advert_detail.getDes());
            etDes.setFilters(new InputFilter[]{new EmojiFilter()});
            etUrl.setText(Advert_detail.getHref());
            etUrl.setFilters(new InputFilter[]{new EmojiFilter()});
            //   ImageLoader.getInstance().load(getContext(), ivAd, Advert_detail.getPic());
            String pic = Advert_detail.getPic();
            if (pic == null || pic.equals("")) {

            } else {
                GlideUtils.loadImageView(getContext(), pic, ivAd);

            }
        } else if (Advert_detail == null) {
            Advert_detail = new AdBannerInfo.AdvertDetailBean();
            info.setAdvert_detail(Advert_detail);
        }
        etServiceName.setFilters(new InputFilter[]{new EmojiFilter()});
        etServiceName.addTextChangedListener(new TextWatcher() {
            private int maxLen = 24;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Editable editable = etServiceName.getText();
                int len = editable.length();
                if (len > maxLen) {
                    ToastUtils.show(getContext(), "输入字符不能超过" + maxLen + "个");
                    int selEndIndex = Selection.getSelectionEnd(editable);
                    String str = editable.toString();
                    //截取新字符串
                    String newStr = str.substring(0, maxLen);
                    etServiceName.setText(newStr);
                    editable = etServiceName.getText();

                    //新字符串的长度
                    int newLen = editable.length();
                    //旧光标位置超过字符串长度
                    if (selEndIndex > newLen) {
                        selEndIndex = editable.length();
                    }
                    //设置新光标所在的位置
                    Selection.setSelection(editable, selEndIndex);

                }

            }

            @Override
            public void afterTextChanged(Editable s) {
                Advert_detail.setName(s.toString());
                info.setAdvert_detail(Advert_detail);
            }
        });
        etDes.addTextChangedListener(new TextWatcher() {
            private int maxLen = 50;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Editable editable = etDes.getText();
                int len = editable.length();
                if (len > maxLen) {
                    ToastUtils.show(getContext(), "输入字符不能超过" + maxLen + "个");
                    int selEndIndex = Selection.getSelectionEnd(editable);
                    String str = editable.toString();
                    //截取新字符串
                    String newStr = str.substring(0, maxLen);
                    etDes.setText(newStr);
                    editable = etDes.getText();

                    //新字符串的长度
                    int newLen = editable.length();
                    //旧光标位置超过字符串长度
                    if (selEndIndex > newLen) {
                        selEndIndex = editable.length();
                    }
                    //设置新光标所在的位置
                    Selection.setSelection(editable, selEndIndex);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
//                    merchantArticleGraphicModel.setGraphicDescription(s.toString());
//                    adInfo.setMerchantArticleGraphicModel(merchantArticleGraphicModel);

                Advert_detail.setDes(s.toString());
                info.setAdvert_detail(Advert_detail);
            }
        });
        etUrl.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String str = s.toString();
//                    if (advertDetailBean == null) {
//                        advertDetailBean = new AdBannerInfo.AdvertDetailBean();
//                    }
                if (str.contains("【")
                        || str.contains("】")
                        || str.contains("，")
                        || str.contains("：")
                        || str.contains("；")) {
                    ToastUtils.show(getContext(), "链接不能包含特殊字符");
                }
                Advert_detail.setHref(str.toString());
                info.setAdvert_detail(Advert_detail);
            }
        });
//            info.setCheckShow(0);
        sbSwitch.setChecked(BooleanUtils.intToBool(info.getIs_carousel()));
        setSbSwitchText(sbSwitch.isChecked(), 0);
        sbSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                info.setIs_carousel(BooleanUtils.BoolToInt(isChecked));
//                    info.setCheckShow(adInfo.getCheckShow() +1);
//                    setSbSwitchText(isChecked,adInfo.getCheckShow());
            }
        });

        cbUseSpace.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                flag = !flag;
                cbUseSpace.setChecked(flag);
       /*         final User user = null;
                if (user != null) {
                    if (!user.getIsHaveHomePage()) {
                        ToastUtils.show(getContext(), "您暂未开通形象空间，请前往 我的-形象空间 设置。");
                    }
                }*/
//                    if (isChecked) {
//                        String url = Config.SPACE_SHARE_URL + "?merchantid=" + CommonUtils.getUserId();
////                        advertDetailBean.s(url);
////                        adInfo.setMerchantArticleGraphicModel(merchantArticleGraphicModel);
////                        etUrl.setText(url);
//                    } else {
//                        merchantArticleGraphicModel.setGraphicUrl("");
//                        adInfo.setMerchantArticleGraphicModel(merchantArticleGraphicModel);
//                        etUrl.setText("");
//                    }
                if (isChecked) {
                    int uid = SharedPreferenceUtils.getMemberId(getContext());
//                    String url = "http://com.ledianduo.com/xxkj/index.html?MerchantId="+uid;
//                    String url= CommonUtils.getLddConfig().getCdnSite()+"/xxkj/index.html?MerchantId="+ uid;
                    String url = SharedPreferenceUtils.getSpaceImageUrl(getContext());
                    info.getAdvert_detail().setHref(url);
                    etUrl.setText(url);
                } else {
                    info.getAdvert_detail().setHref("");
                    etUrl.setText("");
                }
            }
        });
    }

    public void setSbSwitchText(boolean isCheck, int checkShow) {
        if (isCheck) {
            tvSwitchInfo.setText(R.string.ad_on_tip);
            if (checkShow > 0) {
                ToastUtils.show(getContext(), R.string.to_show);
            }

        } else {
            tvSwitchInfo.setTextColor(this.getResources().getColor(R.color.new_black));
            tvSwitchInfo.setTextSize(14);
            tvSwitchInfo.setText(R.string.ad_off_tip);
            if (checkShow > 0) {
                tvSwitchInfo.setTextColor(this.getResources().getColor(R.color.new_black));
                tvSwitchInfo.setTextSize(14);
                ToastUtils.show(getContext(), R.string.to_hide);
            }

        }
//        LddConfig lddConfig = merchantToolSysConfigPresenter.getConfig();
//        if(lddConfig != null){
        tvDes.setClickable(true);
//            tvDes.setText(getClickableSpan(lddConfig.getGraphicDisplayWords(),lddConfig.getGraphicLinkUrl()));
        tvDes.setMovementMethod(LinkMovementMethod.getInstance());
//        }
    }


    public void setOnClickListener(final OnClickListener listener) {
        ibClose.setOnClickListener(listener);
        ivAd.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.onClick(flGraphicPicAdd);
            }
        });
        flGraphicPicAdd.setOnClickListener(listener);
    }

    public void setImage(String url) {
        //  ImageLoader.getInstance().load(getContext(), ivAd, url);
        GlideUtils.loadImageView(getContext(), url, ivAd);

        if (adBannerInfo != null && adBannerInfo.getAdvert_detail() != null) {
            adBannerInfo.getAdvert_detail().setPic(url);
        } else {
            AdBannerInfo.AdvertDetailBean advertDetailBean = new AdBannerInfo.AdvertDetailBean();
            advertDetailBean.setPic(url);
            advertDetailBean.setHref("");
            advertDetailBean.setName("");
            advertDetailBean.setDes("");
            adBannerInfo.setAdvert_detail(advertDetailBean);
        }
    }
}
